<?php
header('Content-type: application/x-javascript'); 

if (file_exists('local_config.php')) include_once('local_config.php');
else include_once('local_config.default.php');


if (!($DATABASE_ADDRESS && $DATABASE_LOGIN && $DATABASE_PASSWORD && $DATABASE_DBNAME)) die("alert('Database access information is missing from the configuration file.  Searches can not be performed at this time.');");

include('libs/libSimpleMySQL.php');
include('sql_queries.php');

function base64url_encode($plainText) {
	$base64 = base64_encode($plainText);
	$base64url = strtr($base64, '+/', '-_');
	return ($base64url);   
}
function phpArrayToJSObject ($array) {
	$s = '{';
	foreach ($array as $key => $value) {
		$s.= '"'.addslashes($key).'":"'.addslashes($value).'",';
	}
	$s = substr($s,0,-1).'}';
	return $s;
}

if (!isset($_GET['q']) or !$_GET['q']) {
	echo 'alert("You must provide a search query.");';
	exit;
}

$searchString = $_GET['q'];

//echo "//Search String: [$searchString]\n";

$db = new SimpleMySQLObject();
if (!$db->connect($DATABASE_ADDRESS,$DATABASE_LOGIN,$DATABASE_PASSWORD,$DATABASE_DBNAME)) die("alert('Could not connect to MySQL server');");

if (!$db->tableExists($DATABASE_TABLE_PREFIX."tracks")) {
	$db->disconnect();
	die('alert("The SQL server is missing the tables needed to perform track searches.");');
}

$query = Q_SearchTracks($searchString);
//echo "// Search Query: $query\n";
$db->query($query);
$results = $db->results();
$db->disconnect();


echo "Musiker.modSearch.searchData['$searchString'] = {\n";

for ($i=0;$i<count($results);$i++) {
	$results[$i]->filepath = base64url_encode($MP3_LIBRARY_LOCATION.'/'.$results[$i]->filepath);
	$results[$i]->time = round($results[$i]->time/1000);
	echo "	$i:",phpArrayToJSObject($results[$i]),",\n";
}
echo "	length:$i};\n";
echo "Musiker.modSearch.search('$searchString',true);";
?>